package com.thinkingstar.iads.common.utils;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.util.Random;

import javax.servlet.http.HttpServletResponse;

public class PictureUtil {
	
	public static String createFileName(String file_type){
		StringBuffer file_name = new StringBuffer(System.currentTimeMillis()+new Random().nextInt(100)+"."+file_type);
		return file_name.toString();
	}
	
	
	public static boolean saveFile(HttpServletResponse rep,File file){
		BufferedInputStream bis = null;  
	    BufferedOutputStream bos = null;  
	    try {
			bis = new BufferedInputStream(new FileInputStream(file));
			bos = new BufferedOutputStream(rep.getOutputStream());  
		    byte[] buff = new byte[2048];  
		    int bytesRead;  
		      while (-1 != (bytesRead = bis.read(buff, 0, buff.length))) {  
		    bos.write(buff, 0, bytesRead);  
		        }  
		    bis.close();  
		    bos.close();  
		} catch (Exception e) {
			e.printStackTrace();
		}
		return true;
	}
	
	
	public static boolean storeFile(InputStream is,String name){
		if(is==null){
			return false;
		}
		
		File parentDir=new File(name).getParentFile();
		if(!parentDir.exists()){
			parentDir.mkdirs();
		}
		boolean flag=true;
		FileOutputStream fos=null;
		try {
			fos=new FileOutputStream(name);
			byte[] b = new byte[1024];
			while((is.read(b)) != -1){
			fos.write(b);
			}
			is.close();
			fos.close();
		} catch (Exception e) {
			flag=false;
		}finally{
			if(is!=null){
				try {
					is.close();
				} catch (Exception e) {
					flag=false;
				}
			}
			if(fos!=null){
				try {
					fos.close();
				} catch (Exception e) {
					flag=false;
				}
			}
		}
		return flag;
	}
	
	public static boolean removeFile(String fileName){
		File file=new File(fileName);
		boolean flag=false;
		file.delete();
		try {
			flag=file.delete();
		} catch (Exception e) {
			flag=false;
		}
		return flag;
	}
}
